package com.landscope.issue.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IpKit {
    private static final Log log = LogFactory.get();

    public static String getServiceIp() {
        String ip = "";
        String chinaz = "http://api.k780.com/?app=ip.local&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            //System.out.println(inputLine.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


//        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
//        Matcher m = p.matcher(inputLine.toString());
//        if (m.find()) {
//            String ipstr = m.group(1);
//            ip = ipstr;
//            //System.out.println(ipstr);
//        }
        String str = inputLine.toString();
        log.info("获取的jsonIp:{}",str);
        JSONObject jsonObject = JSONUtil.parseObj(str);
        if (jsonObject.get("result") != null) {
            JSONObject jsonObject1 = jsonObject.getJSONObject("result");
            if (jsonObject1.get("ip") != null) {
                ip = jsonObject1.getStr("ip");
            }
        }
        if (StrUtil.isEmpty(ip))
            ip = getRealIpV3();
        return ip;
    }

    public static String getRealIpV3() {
        String ip = "";
        String chinaz = "https://qifu.baidu.com/?activeKey=SEARCH_IP";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            //System.out.println(inputLine.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String str = inputLine.toString();
        if (str.indexOf("IP地址:") > 0) {
            int s = str.indexOf("qifu__ipResultContent-10v8A", str.indexOf("IP地址:")) + 2;
            int e = str.indexOf("本机", s) - 1;
            ip = str.substring(s, e);
        }
        return ip;
    }
//
//    public static String getRealIpV2(HttpServletRequest request) {
//        String accessIP = request.getHeader("x-forwarded-for");
//        if (null == accessIP)
//            return request.getRemoteAddr();
//        return accessIP;
//    }
//
//    public static String getIpAddress(HttpServletRequest request) {
//        String ip = "";
//        String chinaz = "http://api.k780.com/?app=ip.local&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
//        StringBuilder inputLine = new StringBuilder();
//        String read = "";
//        URL url = null;
//        HttpURLConnection urlConnection = null;
//        BufferedReader in = null;
//        try {
//            url = new URL(chinaz);
//            urlConnection = (HttpURLConnection) url.openConnection();
//            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
//            while ((read = in.readLine()) != null) {
//                inputLine.append(read + "\r\n");
//            }
//            //System.out.println(inputLine.toString());
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        String str = inputLine.toString();
//        JSONObject jsonObject = JSONObject.parseObject(str);
//        if (jsonObject.get("result") != null) {
//            JSONObject jsonObject1 = jsonObject.getJSONObject("result");
//            if (jsonObject1.get("ip") != null) {
//                ip = jsonObject1.getString("ip");
//            }
//        }
//        if (FStringUtil.isEmpty(ip))
//            ip = getRealIpV3();
//        return ip;
//    }
//
//    public static String getLocalIpAddress() {
//        String ip = "";
//        String chinaz = "http://api.k780.com/?app=ip.local&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
//        StringBuilder inputLine = new StringBuilder();
//        String read = "";
//        URL url = null;
//        HttpURLConnection urlConnection = null;
//        BufferedReader in = null;
//        try {
//            url = new URL(chinaz);
//            urlConnection = (HttpURLConnection) url.openConnection();
//            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
//            while ((read = in.readLine()) != null) {
//                inputLine.append(read + "\r\n");
//            }
//            //System.out.println(inputLine.toString());
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        String str = inputLine.toString();
//        JSONObject jsonObject = JSONObject.parseObject(str);
//        if (jsonObject.get("result") != null) {
//            JSONObject jsonObject1 = jsonObject.getJSONObject("result");
//            if (jsonObject1.get("ip") != null) {
//                ip = jsonObject1.getString("ip");
//            }
//        }
//        if (FStringUtil.isEmpty(ip))
//            ip = getRealIpV3();
//        return ip;
//    }


    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getRealIpV2(HttpServletRequest request) {
        String accessIP = request.getHeader("x-forwarded-for");
        if (null == accessIP)
            return request.getRemoteAddr();
        return accessIP;
    }


    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1"))
            ip = "127.0.0.1";
        return ip;
    }

    public static String getLocalIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
    }

    public static String getV4IP() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            //System.out.println(inputLine.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(1);
            ip = ipstr;
            //System.out.println(ipstr);
        }
        return ip;
    }
}
